package ink.lovejinhu.leetcode;

import ink.lovejinhu.common.TreeNode;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * @author jinhu
 * created 2021-07-21 8:52
 */
public class Solution_0501 {
    /**
     * 二叉搜索树中的众数
     *
     * @param root
     * @return
     */
    public int[] findMode(TreeNode root) {
        this.dfs(root);

        int max = 0;
        for (int v : map.keySet()
        ) {
            if (map.get(v) >= max) {
                max = map.get(v);
            }
        }
        ArrayList<Integer> integers = new ArrayList<>();
        for (int v : map.keySet()
        ) {
            if (map.get(v) == max) {
                integers.add(v);
            }
        }
        int[] ints = new int[integers.size()];
        for (int i = 0; i < ints.length; i++) {
            ints[i] = integers.get(i);

        }
        return ints;
    }


    public HashMap<Integer, Integer> map = new HashMap<>();

    public void dfs(TreeNode root) {
        if (root == null) return;
        if (map.containsKey(root.val)) {
            Integer integer = map.get(root.val);
            map.put(root.val, integer + 1);
        } else {
            map.put(root.val, 1);
        }
        dfs(root.left);
        dfs(root.right);
    }
}
